/**
 * Created by zzy on 2017/8/28.
 */
import React, {Component} from 'react';
import {
    Text,
    View,
    TouchableOpacity,
    Image,
    StyleSheet,
    ScrollView,
    Dimensions,
    FlatList,
    PixelRatio,
    InteractionManager,
    DeviceEventEmitter
} from 'react-native';
import Constant from '../Contant'
import Icon from 'react-native-vector-icons/Ionicons'
import DeliverTimeChooser from '../component/DeliverTimechooser'
import ItemCell from '../component/ItemCell'
import InvoiceModal from '../component/InvoiceModal'
import PayTypeModal from '../component/PayTypeModal'
import {GradientButton} from '../component/Button'
import addressMgrStore from '../store/AddrMgrStore'
import NetRequest from '../util/NetRequest'
import {observer} from 'mobx-react/native'
import {observable, action, computed} from 'mobx'
import LoadingView from '../component/LoadingView'
import DialogModal from '../component/DialogMadal'
import waterShopStore from '../store/WaterShopStore'
import Toast from 'react-native-easy-toast'
import {Option,PriceLabel} from '../home/ShoppingCart'
import RequestUtil from "../util/NetUtil";
import shoppingCartStore from '../../luojs/store/ShoppingCartStore'
let {width} = Dimensions.get('window');
@observer
export default class ConfirmOrder extends Component {
    @observable loading = false;
    static navigationOptions = {
        title: '确认订单'
    };

    constructor(props) {
        super(props);
        this.state = {
            deliveryTime: '全天',
            payType: '在线支付',
            orderProductInfo: {totalCount: 0, totalPrice: 0, totalPayMount: 0, productItemModels: [{currentPrice:'',productType:''}]},
            orderTicketInfo: {totalUsed: 0, userTicketModels: []},
            shopName: ''
        };
        this.shopId = this.props.navigation.state.params.shopId;
        this.userTicketId = this.props.navigation.state.params.userTicketId;
        this.productItemId = this.props.navigation.state.params.productItemId;

        // 是否通过使用水票界面过来
        this.payByTicket = this.userTicketId != null;

        this.singleProduct=this.productItemId!=null;
    }


    // 商品的加减
    updateProduct(product,type='increase') {
        if(this.shopId!= null){
            RequestUtil.requestData('shop/shoppingcart/' + type, {
                "productItemId": product.productItemId,
                "productType": product.type||'entityProduct',
                "shopId": this.shopId,
            }).then(resp => {
                LOG('increaseOrdecrease:' + JSON.stringify(resp));
                this._confirmOrderInfo('default');
            })
        }
    }

    render() {
        return <View style={{backgroundColor: '#f5f5f5', flex: 1}}>
            <LoadingView
                visible={this.loading}
                color="white"
                indicatorSize="small"
                messageFontSize={12}
                message='正在处理...'
            />
            <ScrollView style={{backgroundColor: Constant.GRAYBGCOLOR}}>

                {
                    this.payUserInfoView()
                }
                <ShopConfirmCell
                    increase={(product) => {
                        this.updateProduct(product);
                    }}
                    decrease={(product) => {
                        if(product.selectCount<=1)return;
                        this.updateProduct(product,'decrease');
                    }}
                    shopId={this.shopId}
                    shopName={this.state.shopName}
                    orderProductInfo={this.state.orderProductInfo}
                    orderTicketInfo={this.state.orderTicketInfo}
                    payBuyTicket={this.payByTicket}
                    singleProduct={this.singleProduct}
                    navigate={this.props.navigation.navigate}/>
            </ScrollView>
            <ComfirmOrderFooter
                navigate={this.props.navigation.navigate}
                createOrder={this._enSurePay.bind(this)}
                totalCount={this.state.orderProductInfo.totalCount}
                totalPayMount={this.state.orderProductInfo.totalPayMount}/>
            <DeliverTimeChooser
                ref="deliverTimeModal"
                callbcak={this._timeData.bind(this)}
            />
            <InvoiceModal
                ref={"invoiceModal"}
                callbcak={this._invoiceData.bind(this)}
            />
            <PayTypeModal ref={"payTypeModal"} callbcak={this._payTypeData.bind(this)}/>
            <DialogModal
                ref={"dialogModal"}
                totalUsed={this.state.orderTicketInfo.totalUsed}
                callbcak={this._createOrder.bind(this)}/>
            <Toast ref="toast" position='center'/>
        </View>
    }

    payUserInfoView(){
        if(this.isSingleTiket()){//单独立即支付不显示收货地址等信息
            return (null);
        }else {
            return <View>
                <HeadeAddrView navigate={this.props.navigation.navigate}
                               address={addressMgrStore.deliveryAddressListMgr.SelectedAddress}/>
                <HeaderDeliveryTimeView
                    showTime={this._showTimeModal.bind(this)}
                    time={this.state.deliveryTime}/>
                <View style={{marginTop: 1}}>
                    <ItemCell
                        name={'支付方式'}
                        desc={this.state.payType}
                        //callback={this._showPayTypeModal.bind(this)}
                    />
                </View>
                <View style={{marginTop: 20}}>
                    <ItemCell
                        name={'发票'}
                        desc={'不开发票'}
                        callback={this._showInvoiceModal.bind(this)}
                    />
                </View>
            </View>;
        }
    }
    isSingleTiket(){
        return this.singleProduct&&this.state.orderProductInfo.productItemModels[0].productType=='水票'
    }
    /**
     * 配送时间选择的显示 隐藏
     * @private
     */
    _showTimeModal() {
        this.refs.deliverTimeModal.openModal();
    }

    _showInvoiceModal() {
        this.refs.invoiceModal.openModal();
    }

    _showPayTypeModal(payType) {
        this.refs.payTypeModal.openModal();
    }

    _showTiketPayModal() {
        this.refs.dialogModal.openModal();
    }

    _invoiceData(data) {
        //返回发票信息
    }

    _timeData(data) {
        //返回配送时间
        console.log('时间-------------' + data);
        this.setState({
            deliveryTime: data
        })
    }

    _payTypeData(data) {
        //返回支付方式
        console.log('支付方式-------------' + data);
        this.setState({
            payType: data
        })
    }

    componentDidMount() {
        this.refreshOrderInfo = DeviceEventEmitter.addListener('refreshOrderInfo', () => {
            this._confirmOrderInfo(null);//水票操作后获取orderinfo传null获取操作后的支付信息
        });
        this.payComplete = DeviceEventEmitter.addListener('payComplete', () => {
            this.props.navigation.goBack();
        });
        this.loginin = DeviceEventEmitter.addListener(Constant.LOGINOK,()=>{
            this._confirmOrderInfo('default');//首次获取orderinfo传default获取水票使用最大匹配的支付信息
        });
    }
    componentWillMount() {
        this._confirmOrderInfo('default');//首次获取orderinfo传default获取水票使用最大匹配的支付信息
    }
    componentWillUnmount() {
        this.refreshOrderInfo.remove();
        this.payComplete.remove();
        this.loginin.remove();
    }

    _confirmOrderInfo(init) {
        let param = {};
        // 立即使用水票
        if (this.payByTicket) {
           param = {
                userTicketId: this.userTicketId
            }
        }else if(this.singleProduct){//单独购买商品需要用productItemId匹配商品
            param = {
                productItemId: this.productItemId
            }
        }
        else {
           param = {
                shopId: this.shopId
            }
        }
        InteractionManager.runAfterInteractions(() => {
            this.loading = true;
            NetRequest.confirmOrderInfo(param, init).then((resp) => {
                LOG('确认订单--------' + JSON.stringify(resp));
                this.loading = false;
                this.setState({
                    orderProductInfo: resp.orderProductInfo,
                    orderTicketInfo: resp.orderTicketInfo,
                    shopName: resp.shopName
                })

                this.shopId = resp.shopId ;
            }).catch(err=>{
                this.loading = false;
                this.props.navigation.navigate('Login');
            })
        });
    }

    _enSurePay() {
        if(this.state.shopName=='')return;
        if (this.state.orderProductInfo.totalPayMount == 0) {
            this.refs.dialogModal.openModal();
            return;
        }
        this._createOrder();
    }

    _createOrder() {
        if (addressMgrStore.deliveryAddressListMgr.SelectedAddress == null&&!this.isSingleTiket()) {
            this.refs.toast.show('请创建收货地址');
            return;
        }
        this.loading = true;
        if(this.payByTicket){
            //水票列表 立即使用
            this.confirmOrderPayByTicket();
        }
        else {
            let orderParam = {
                deliveryAddressId: addressMgrStore.deliveryAddressListMgr.SelectedAddress!=null?addressMgrStore.deliveryAddressListMgr.SelectedAddress.id:0,
                payType: this.state.payType == '在线支付' ?  Constant.ONLINEPAY : Constant.OFFLINEPAY,
                shopId: this.shopId,
                deliveryTime:this.state.deliveryTime,
                productItemId:null
            };
            if(this.singleProduct){//单独购买商品需要加productItemId
                orderParam.productItemId=this.productItemId;
            }
            NetRequest.createOrder(orderParam).then((data) => {
                LOG('生成订单---------' + JSON.stringify(data));
                this.loading = false;
                if(data.message=!null&&data.message=='有正在支付的订单'){
                    this.refs.toast.show('有正在支付的订单');
                    return;
                }
                this.quickPay(data) ;
            });
        }
    }

    // 去支付
    quickPay(data,channel='CardTicket'){
        DeviceEventEmitter.emit('refreshShopList');//刷新购物车
        waterShopStore.resetShoppingCart();
        shoppingCartStore.getShoppingCart();
        let {orderNo, totalPrice, orderId,payType} = data;
        if (totalPrice == 0) {
            this.props.navigation.navigate('PayResult', {
                payInfo: {
                    orderId: orderNo,
                    channel: channel
                }
            });
            return;
        }
        this.props.navigation.navigate('QuickPay', {orderNo: orderNo, orderId: orderId, totalPrice: totalPrice});
    }

    // 获取待支付商品ID
    getProductId(){
        let ids = [] ;
        this.state.orderProductInfo.productItemModels.forEach(item=>{
            ids.push(item.productItemId);
        })
        return ids[0] ;
    }


    // 水票确认订单
    confirmOrderPayByTicket(){
        RequestUtil.requestData('order/create', {
            deliveryAddressId: addressMgrStore.deliveryAddressListMgr.SelectedAddress.id,
            payType: this.state.payType == '在线支付' ? Constant.ONLINEPAY : Constant.OFFLINEPAY,
            productItemId: this.getProductId(),
            shopId: this.shopId
        }).then(resp => {
            LOG('水票确认订单:' + JSON.stringify(resp));
            this.loading = false;
            this.quickPay(resp,'CardTicket') ;
        })
    }
}

class ShopConfirmCell extends Component {
    render() {
        let {orderProductInfo, orderTicketInfo, shopId, shopName, increase, decrease,payBuyTicket,singleProduct} = this.props;
        return <View style={{marginBottom: 10, backgroundColor: '#fff', marginTop: 20}}>
            <ShopConfirmHeader shopName={shopName}/>
            {
                orderProductInfo.productItemModels.map((p, index) => {
                    return <ProductItemCell
                        minus={() => {
                            decrease(p);
                        }}
                        plus={() => {
                            increase(p);
                        }}
                        product={p}
                        key={index}
                        payBuyTicket={payBuyTicket}
                        singleProduct={singleProduct}
                    />
                })
            }
            <ShopConfirmFooter
                payBuyTicket={payBuyTicket}
                singleProduct={singleProduct}
                navigate={this.props.navigate}
                orderTicketInfo={orderTicketInfo}
                orderProductInfo={orderProductInfo}
                shopId={shopId}/>
        </View>
    }
}
const ProductItemCell = observer(({product,minus,plus,payBuyTicket,singleProduct})=>{
    let sourceIcon;
    product.productType=='水票'?sourceIcon=require('../../luoasserts/tiket/goods_ticket_bg.png'):sourceIcon={uri:product.productImage==null?'':product.productImage[0]};
    return <TouchableOpacity
        activeOpacity={0.9}
        onPress={()=>{

        }}
        style={{flexDirection:'row',paddingVertical:10,alignItems:'center'}}>
        <View style={{flex:9}}>
            <View style={{flexDirection:'row',justifyContent:'space-between'}}>
                <View style={{flexDirection:'row'}}>
                    <View>
                        <Image
                            defaultSource={require('../../asserts/common/default_productItem.png')}
                            resizeMode='contain'
                            style={{
                                width: width * 0.8 * 0.3 - 10,
                                height: width * 0.8 * 0.3 - 10,
                            }}
                            source={sourceIcon}/>
                    </View>
                    <View style={{justifyContent:'space-around',paddingLeft:10}}>
                        <Text style={{color:Constant.TEXT_COLOR_2,fontSize:16}}>{product.name}</Text>
                        <Text style={{color:Constant.TEXT_COLOR_6,fontSize:12}}></Text>
                        <View style={{flexDirection:'row',alignItems:'center'}}>
                            <PriceLabel price={product.currentPrice}/>
                            <Text style={{color:Constant.TEXT_COLOR_6,fontSize:12}}>x{product.selectCount}</Text>
                        </View>
                    </View>
                </View>
                <View style={{justifyContent:'flex-end',paddingRight:15}}>
                    {
                        payBuyTicket||singleProduct?<Option
                            selectCount={product.selectCount}
                            minus={minus}
                            plus={plus}
                        />:(null)
                    }
                </View>
            </View>
            <View style={styles.separatorLine}/>
        </View>
    </TouchableOpacity>
})

class ShopConfirmFooter extends Component {
    render() {
        let {orderProductInfo, orderTicketInfo, shopId,payBuyTicket,singleProduct} = this.props;
        return <View>
            {
                singleProduct&&orderProductInfo.productItemModels[0].productType=='水票'?(null):<ItemCell name={'水票抵用'} desc={orderTicketInfo.totalUsed + '张'} callback={() => {
                    if(payBuyTicket)return;
                    this.props.navigate('TiketsViable', {orderTicketInfo: orderTicketInfo, shopId: shopId});
                }}/>
            }
            <View style={{
                flexDirection: 'row',
                borderBottomColor: '#e3e3e3',
                borderBottomWidth: 1 / PixelRatio.get(),
                padding: 10,
                justifyContent: 'flex-end',
                alignItems:'center'
            }}>
                <Text>共{orderProductInfo.totalCount}件商品，合计: </Text>
                <PriceLabel price={orderProductInfo.totalPrice}/>
            </View>
        </View>
    }
}

class ShopConfirmHeader extends Component {
    render() {
        let {shopName} = this.props;
        let shopIcon = require('../../asserts/order/tab_icon_water_station_s.png');
        return <View style={{}}>
            <ItemCell icon={shopIcon} iconStyle={{height: 20, width: 20}} name={shopName} rightArrowShow={false}/>
        </View>
    }
}

class HeaderDeliveryTimeView extends Component {
    render() {
        return <TouchableOpacity
            onPress={this.props.showTime}
            activeOpacity={1}
            style={[styles.row, {
                justifyContent: 'space-between',
                paddingVertical: 10,
                paddingHorizontal: 10,
                alignItems: 'center',
                backgroundColor: 'white'
            }]}>
            <View>
                <Text style={{fontSize: 14}}>配送时间</Text>
            </View>
            <View style={[styles.row, {alignItems: 'center'}]}>
                <Text style={{fontSize: 12}}>{this.props.time}</Text>
                <View style={{paddingLeft: 10}}>
                    <Icon name="ios-arrow-forward-outline" color="gray" size={28}/>
                </View>
            </View>
        </TouchableOpacity>
    }
}

class HeadeAddrView extends Component {
    render() {
        let {navigate, address} = this.props;
        return <View>
            {
                addressMgrStore.deliveryList.length != 0 ? <TouchableOpacity
                    style={[styles.row, {
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        paddingHorizontal: 10,
                        marginTop: 20,
                        backgroundColor: 'white'
                    }]}
                    activeOpacity={1}
                    onPress={() => {
                        navigate('AddressList');
                        addressMgrStore.deliveryAddressListMgr.setIsSelectAddress(true);
                    }}>
                    <View>
                        <View style={[styles.row, {justifyContent: 'space-between', paddingVertical: 10}]}>
                            <View style={styles.row}>
                                <Text style={{fontSize: 13}}>收货人：</Text>
                                <Text style={{fontSize: 12}}>{address.name}</Text>
                            </View>
                            <View style={{paddingRight: 10}}>
                                <Text style={{fontSize: 13}}>{address.phoneNum}</Text>
                            </View>
                        </View>
                        <View style={[styles.row, {paddingBottom: 10}]}>
                            <Text style={{fontSize: 14}}>送货地址：</Text>
                            <Text style={{width: width - 100, fontSize: 12}}
                                  numberOfLines={2}>{address.address.mapAddress + address.address.appendingAddress}</Text>
                        </View>
                    </View>
                    <View>
                        <Icon name="ios-arrow-forward-outline" color="gray" size={28}/>
                    </View>
                </TouchableOpacity> : <View style={{backgroundColor: 'white', height: 50, justifyContent: 'center'}}>
                    <ItemCell name={'创建收货地址'} callback={() => {
                        navigate('AddressList');
                    }}/>
                </View>

            }
            <Image style={{height: 2, width: width, resizeMode: 'cover'}}
                   source={require('../../asserts/order/top_sep_line.png')}/>
        </View>
    }
}

class ComfirmOrderFooter extends Component {


    render() {
        let {navigate, createOrder, totalCount, totalPayMount} = this.props;
        return <View style={{
            height: 46,
            backgroundColor: 'white',
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between'
        }}>
            <View style={{flexDirection: 'row', marginLeft: 10, flex: 2}}>
                <TouchableOpacity style={[styles.footerItem, styles.center]}>
                    <View style={[{flexDirection: 'row'}, styles.center]}>
                        <Text style={[{paddingHorizontal: 10}]}>共{totalCount}件</Text>
                    </View>
                </TouchableOpacity>
                <View style={{alignItems: 'center', marginHorizontal: 10, flexDirection: 'row'}}>
                    <Text>实付款: </Text>
                    <PriceLabel price={totalPayMount}/>
                </View>
            </View>

            <View style={{flex: 1}}>
                <GradientButton round={false} title="提交订单" colors={['#ff680f', '#ff2d2d']} onPress={() => {
                    createOrder();
                }}/>
            </View>
        </View>
    }
}

const styles = {
    borderBottom: {
        borderBottomColor: '#f5f5f5',
        borderBottomWidth: 1 / PixelRatio.get()
    },
    center: {
        alignItems: 'center',
        justifyContent: 'center'
    },
    footerText: {
        color: '#fff',
        fontSize: 15
    },
    footerItem: {
        height: 40
    },
    footerItemText: {
        color: 'gray',
        fontSize: 13
    },
    row: {flexDirection: 'row'}
}